package net.lcqf.tcp.send.message;

import cn.hutool.json.JSONUtil;
import io.netty.channel.Channel;
import net.lcqf.tcp.constants.Constants;
import net.lcqf.tcp.game.MatchRoom;
import net.lcqf.tcp.game.match.MatchFactory;
import net.lcqf.tcp.game.match.model.MatchPlayer;
import net.lcqf.tcp.game.match.model.Team;
import net.lcqf.tcp.game.room.RoomManager;
import net.lcqf.tcp.request.MatchRequest;
import net.lcqf.tcp.response.MatchResponse;
import net.lcqf.tcp.response.room.ReadyRoomResponse;;
import net.lcqf.tcp.send.MessageBaseService;
import net.lcqf.tcp.send.MessageFactory;
import net.lcqf.tcp.send.RequestType;
import net.lcqf.tcp.utils.LocalCacheUtil;
import net.lcqf.tcp.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 玩家组队匹配 1v1 3v3 5v5
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2021-2025 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2025/2/19 11:18
 * // +----------------------------------------------------------------------
 */

@Service
public class Match implements MessageBaseService {

    private static final Logger logger = LoggerFactory.getLogger(Match.class);

    private final MatchFactory matchFactory;

    private final RedisUtil redisUtil;

    public Match(MatchFactory matchFactory, RedisUtil redisUtil) {
        this.matchFactory = matchFactory;
        this.redisUtil = redisUtil;
    }

    @Override
    @PostConstruct
    public void init() {
        MessageFactory.register(RequestType.MATCH, this);
    }

    @Override
    public Object sendMessage(Channel channel, String msg) {
        MatchRequest request = JSONUtil.toBean(msg, MatchRequest.class);

        MatchResponse match = new MatchResponse();
        match.setType(request.getType());
        match.setWaitTime(Constants.NUM_FIFTEEN);

        boolean result = checkPlayerBehavior(request, channel);
        match.setResult(result);

        return match;
    }

    /**
     * TODO 检测玩家的匹配行为
     * @param request 请求参数
     * @param channel 消息通道
     */
    private boolean checkPlayerBehavior(MatchRequest request, Channel channel) {
        switch (request.getType()) {
            case 0:
                // 模拟匹配玩家数据
                int id = LocalCacheUtil.ATOMIC.getAndIncrement();
                MatchPlayer player = new MatchPlayer();
                player.setId(id);
                player.setAvatar("https://ac.lcqf.net/h5/avatar.jpg");
                player.setUserName(request.getUserName());
                player.setChannel(channel);
                player.setChannelId(channel.id().asShortText());
                player.setReady(false);
                player.setElo(1500 + id*10);
                player.setJoinTime(System.currentTimeMillis());
                return matchFactory.addPlayer(request.getTeamType(), player);
            case 1:
                return matchFactory.removePlayer(request.getTeamType(), channel.id().asShortText());
            default:
                // 其他行为，直接断开连接
                if (channel.isActive()) { channel.close(); }
                //return false;
        }

        return false;
    }


    /**
     * 1v1 3v3 5v5 组队匹配成功回调
     * @param teamA a
     * @param teamB b
     * @param teamType 组队方式
     */
    public void onMatchSuccess(Team teamA, Team teamB, String teamType) {
        logger.info("组队方式：" + teamType);
        logger.info("TeamA: " + teamA);
        logger.info("TeamB: " + teamB);


        List<MatchPlayer> matchPlayerList = new CopyOnWriteArrayList<>(teamA.getPlayers());
        matchPlayerList.addAll(teamB.getPlayers());

        int roomId = LocalCacheUtil.ROOM.incrementAndGet();

        ReadyRoomResponse readyRoom = new ReadyRoomResponse();
        readyRoom.setRoomId(roomId);
        readyRoom.setReadyNum(matchPlayerList.size());
        readyRoom.setTeamType(teamType);
        readyRoom.setTeamA(teamA.getPlayers());
        readyRoom.setTeamB(teamB.getPlayers());

        // 发送给全部玩家
        MatchRoom.broadcastToPlayer(RequestType.READY_ROOM.ordinal(), JSONUtil.toJsonStr(readyRoom), matchPlayerList);


        // 创建房间
        RoomManager room = new RoomManager(roomId, matchPlayerList);
        LocalCacheUtil.ACTIVE_ROOM.put(roomId, room);
    }

    /**
     * 十六进制转10进制
     * @param hex 转换的数据
     * @return {@code long}
     */
    private long hexToDecimal(String hex) {
        long decimal = 0;
        String digits = "0123456789abcdef";
        for (int i = 0; i < hex.length(); i++) {
            char c = hex.charAt(i);
            int d = digits.indexOf(c);
            decimal = decimal * 16 + d;
        }
        return decimal;
    }

}
